package ee.homework.sixth;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HashFunction {
	private List<Long> keys;

	public static void main(String[] args) {
		HashFunction hf = new HashFunction();
		hf.readKeys();
		hf.run();
	}

	private void run() {
		long p = 1212839;
		int size = 200;
		long a = 580180;
		long b = 733839;
		collisions(a, b, p, size);
	}

	private void collisions(long a, long b, long p, int size) {
		int[] collisions = new int[200];
		Integer h;
		for (Long integer : keys) {
			h = universalHash(a, integer, b, p, size);
			int col = collisions[h] + 1;
			collisions[h] = col;
		}
		int max = 0;
		for (int i = 0; i < collisions.length; i++) {
			if (collisions[i] > max) {
				max = collisions[i];
			}
		}
		System.out.println("Max collisions: " + max);
	}

	private int universalHash(long a, long k, long b, long p, int size) {
		return (int) (((a * k + b) % p) % size);
	}

	private void readKeys() {
		try {
			BufferedReader reader = new BufferedReader(new FileReader(new File(
					"data\\keys.txt")));
			String line = null;
			keys = new ArrayList<Long>();
			while ((line = reader.readLine()) != null) {
				keys.add(Long.parseLong(line.trim()));
			}
		} catch (IOException e) {
			System.out.println("Error occurred while trying to read file: "
					+ e.getMessage());
		}
	}

}
